package com.kyzh.core.dialog

import android.annotation.SuppressLint
import android.text.Html
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.gushenge.atools.ui.ArcButton
import com.gushenge.core.beans.DownTaskBean
import com.gushenge.core.beans.UpdateAppBean
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.MyApplication
import com.kyzh.core.R
import com.kyzh.core.download.down.DownTask
import com.kyzh.core.uis.AnimDownloadProgressButton
import org.jetbrains.anko.sp


private var updateDialog:AlertDialog?=null

fun AppCompatActivity.showUpdateDialog(data: UpdateAppBean,listener:() ->Unit){
    updateDialog = AlertDialog.Builder(this, R.style.updateDialog)
            .setView(getView(data,listener))
            .setCancelable(!data.constraint)
            .create()

    updateDialog?.show()
}
@SuppressLint("ClickableViewAccessibility")
private fun AppCompatActivity.getView(data: UpdateAppBean, listener:() ->Unit):View{
    val view = LayoutInflater.from(this).inflate(R.layout.dialog_update, null)

    val desc = view.findViewById<TextView>(R.id.tvDesc)
    val cancel = view.findViewById<ArcButton>(R.id.tvCancel)
    val start = view.findViewById<AnimDownloadProgressButton>(R.id.tvUpdate)

    start.textSize = sp(14).toFloat()
    desc.text = Html.fromHtml(data.update_log)
    desc.isVerticalScrollBarEnabled = true;
    desc.movementMethod = ScrollingMovementMethod.getInstance()
    cancel.setOnClickListener {
        updateDialog?.dismiss()
        listener()
    }
    if (data.constraint){
        cancel.visibility =View.GONE
    }

    start.setCurrentText(getString(R.string.updateNow))
    start.setOnClickListener {
        val game1 = DownTaskBean()
        game1.url = data.apk_file_url
        game1.size = data.target_size
        game1.name = data.versionCode
        game1.packageName = MyApplication.instance.packageName
        game1.gid = "0"
        DownTask.downLoad(game1)
    }
    LiveEventBus.get<Map<String, DownTaskBean>>("GAMETASK").observe(this) {
        Log.e("TAG", "initBottom: "+it.size )
        it[data.apk_file_url]?.apply {
            Log.e("TAG", "initBottom: 接收到了"+this.state  +this.process   )
            when(this.state){
                0->  start.setProgressText("下载",this.process)
                1->  {
                    start.setProgressText("下载中${this.process}%",0.2f)
                    start.state = AnimDownloadProgressButton.DOWNLOADING
                }
                2-> start.setProgressText("等待中",this.process)
                3->{
                    start.setProgressText("安装",this.process)
                    start.state = AnimDownloadProgressButton.NORMAL
                }
            }
        }
    }
    return view
}